<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="传感器ID" prop="sensorId">
        <el-input v-model="queryParams.sensorId" placeholder="请输入传感器ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="应用ID" prop="appId">
        <el-input v-model="queryParams.appId" placeholder="请输入应用ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备名称" prop="nodeName">
        <el-input v-model="queryParams.nodeName" placeholder="请输入设备名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="连接状态" prop="connectStatus">
        <el-select v-model="queryParams.connectStatus" placeholder="连接状态" clearable>
          <el-option label="已连接" :value="true" />
          <el-option label="已断开" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="启用状态" clearable>
          <el-option label="启用" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <!-- 在操作按钮区域添加 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button 
          :type="autoRefreshEnabled ? 'success' : 'info'" 
          plain 
          :icon="autoRefreshEnabled ? 'el-icon-video-play' : 'el-icon-video-pause'" 
          size="mini" 
          @click="toggleAutoRefresh"
        >
          {{ autoRefreshEnabled ? '停止自动刷新' : '开启自动刷新' }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-refresh" size="mini" @click="handleRefresh">刷新</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="deviceDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="传感器ID" align="center" prop="sensorId" width="120" />
      <el-table-column label="应用ID" align="center" prop="appId" width="120" />
      <el-table-column label="设备节点ID" align="center" prop="nodeId" width="100" />
      <el-table-column label="设备名称" align="center" prop="nodeName" width="150" />
      <el-table-column label="设备描述" align="center" prop="description" width="200" show-overflow-tooltip />
      <el-table-column label="厂商ID" align="center" prop="manufacturerId" width="100" />
      <el-table-column label="设备型号" align="center" prop="model" width="120" />
      <el-table-column label="经度" align="center" prop="longitude" width="100" />
      <el-table-column label="纬度" align="center" prop="latitude" width="100" />
      <el-table-column label="位置名称" align="center" prop="fullName" width="150" show-overflow-tooltip />
      <el-table-column label="省市编码" align="center" prop="proviceCode" width="100" />
      <el-table-column label="市编码" align="center" prop="cityCode" width="100" />
      <el-table-column label="区县编码" align="center" prop="regionCode" width="100" />
      <el-table-column label="连接状态" align="center" prop="connectStatus" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.connectStatus ? 'success' : 'danger'">
            {{ scope.row.connectStatus ? '已连接' : '已断开' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updateBy" width="100" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="150" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="传感器ID" prop="sensorId">
              <el-input v-model="form.sensorId" placeholder="请输入传感器ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用ID" prop="appId">
              <el-input v-model="form.appId" placeholder="请输入应用ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备节点ID" prop="nodeId">
              <el-input-number v-model="form.nodeId" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="nodeName">
              <el-input v-model="form.nodeName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="厂商ID" prop="manufacturerId">
              <el-input-number v-model="form.manufacturerId" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入设备型号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input-number v-model="form.longitude" :precision="6" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input-number v-model="form.latitude" :precision="6" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="位置名称" prop="fullName">
          <el-input v-model="form.fullName" placeholder="请输入位置名称" />
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="省份编码" prop="proviceCode">
              <el-input v-model="form.proviceCode" placeholder="请输入省份编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="城市编码" prop="cityCode">
              <el-input v-model="form.cityCode" placeholder="请输入城市编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区县编码" prop="regionCode">
              <el-input v-model="form.regionCode" placeholder="请输入区县编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="连接状态" prop="connectStatus">
              <el-radio-group v-model="form.connectStatus">
                <el-radio :label="true">已连接</el-radio>
                <el-radio :label="false">已断开</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="设备描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入设备描述" :rows="3" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 设备详情查看对话框 -->
    <el-dialog title="设备详情" :visible.sync="viewOpen" width="1200px" append-to-body>
      <div v-if="currentDevice">
        <!-- 设备基本信息 -->
        <el-card class="box-card" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">设备基本信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">传感器ID：</span>
                <span class="info-value">{{ currentDevice.sensorId }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">设备名称：</span>
                <span class="info-value">{{ currentDevice.nodeName }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">连接状态：</span>
                <el-tag :type="currentDevice.connectStatus ? 'success' : 'danger'">
                  {{ currentDevice.connectStatus ? '已连接' : '已断开' }}
                </el-tag>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 15px;">
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">应用ID：</span>
                <span class="info-value">{{ currentDevice.appId }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">设备型号：</span>
                <span class="info-value">{{ currentDevice.model }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">启用状态：</span>
                <el-tag :type="currentDevice.status === 1 ? 'success' : 'info'">
                  {{ currentDevice.status === 1 ? '启用' : '停用' }}
                </el-tag>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 15px;">
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">位置信息：</span>
                <span class="info-value">{{ currentDevice.fullName }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="info-label">设备描述：</span>
                <span class="info-value">{{ currentDevice.description }}</span>
              </div>
            </el-col>
          </el-row>
          
          <!-- 新增：设备位置信息 -->
          <el-row :gutter="20" style="margin-top: 15px;">
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">经度：</span>
                <span class="info-value">{{ currentDevice.longitude || 'N/A' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">纬度：</span>
                <span class="info-value">{{ currentDevice.latitude || 'N/A' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="info-label">详细地址：</span>
                <span class="info-value">{{ currentDevice.fullName || 'N/A' }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 新增：设备位置地图 -->
        <el-card class="box-card" style="margin-bottom: 20px;" v-if="currentDevice.longitude && currentDevice.latitude">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">设备位置</span>
          </div>
          <device-map 
            :single-device="currentDevice" 
            height="300px"
          />
        </el-card>
        
        <!-- 温湿度检测数据 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold;">温湿度检测数据</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshSensorData">
              <i class="el-icon-refresh"></i> 刷新数据
            </el-button>
          </div>

          <!-- 数据加载状态 -->
          <div v-loading="sensorDataLoading">
            <!-- 最新数据概览 -->
            <div v-if="sensorDataList.length > 0" style="margin-bottom: 20px;">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-statistic title="最新温度" :value="sensorDataList[0].temperature" suffix="°C" :precision="2">
                    <template slot="prefix">
                      <i class="el-icon-thermometer" style="color: #f56c6c"></i>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic title="最新湿度" :value="sensorDataList[0].humidity" suffix="%" :precision="2">
                    <template slot="prefix">
                      <i class="el-icon-water" style="color: #409eff"></i>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic title="数据版本" :value="sensorDataList[0].version">
                    <template slot="prefix">
                      <i class="el-icon-document"></i>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic title="采集时间" :value="parseTime(sensorDataList[0].collectTime)">
                    <template slot="prefix">
                      <i class="el-icon-time"></i>
                    </template>
                  </el-statistic>
                </el-col>
              </el-row>
            </div>

            <!-- 历史数据表格 -->
            <el-table :data="sensorDataList" style="width: 100%" max-height="400">
              <el-table-column label="序号" type="index" width="60" align="center" />
              <el-table-column label="客户端ID" prop="clientId" width="120" align="center" />
              <el-table-column label="温度(°C)" prop="temperature" width="100" align="center">
                <template slot-scope="scope">
                  <span :style="{ color: getTemperatureColor(scope.row.temperature) }">
                    {{ scope.row.temperature }}°C
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="湿度(%)" prop="humidity" width="100" align="center">
                <template slot-scope="scope">
                  <span :style="{ color: getHumidityColor(scope.row.humidity) }">
                    {{ scope.row.humidity }}%
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="版本" prop="version" width="80" align="center" />
              <el-table-column label="采集时间" prop="collectTime" width="180" align="center">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.collectTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" prop="createTime" width="180" align="center">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
            </el-table>

            <!-- 无数据提示 -->
            <div v-if="sensorDataList.length === 0" style="text-align: center; padding: 40px;">
              <i class="el-icon-warning" style="font-size: 48px; color: #e6a23c;"></i>
              <p style="margin-top: 16px; color: #909399;">暂无温湿度检测数据</p>
            </div>
          </div>
        </el-card>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listDeviceData, addDeviceDetails, getDeviceDataBySensorId } from "@/api/emqx/deviceDetails"
import DeviceMap from "@/components/DeviceMap"

export default {
  name: "DeviceDetails",
  components: {
    DeviceMap
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      deviceDataList: [],
      // 添加以下新属性
      viewOpen: false,           // 查看对话框显示状态
      currentDevice: null,       // 当前查看的设备信息
      sensorDataList: [],        // 传感器数据列表
      sensorDataLoading: false,  // 传感器数据加载状态
      // 添加自动刷新相关属性
      autoRefreshEnabled: false, // 自动刷新开关
      refreshTimer: null,        // 定时器引用
      refreshInterval: 30000,    // 刷新间隔（30秒）
      title: "",
      open: false,
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sensorId: null,
        appId: null,
        nodeName: null,
        connectStatus: null,
        status: null
      },
      form: {},
      rules: {
        sensorId: [
          { required: true, message: "传感器ID不能为空", trigger: "blur" }
        ],
        nodeName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        appId: [
          { required: true, message: "应用ID不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "设备状态不能为空", trigger: "change" }
        ]
      },
      clientId: [
        { required: true, message: "客户端ID不能为空", trigger: "blur" }
      ]
    }
  },
  created() {
    this.getList();
    this.startAutoRefresh();  // 启动自动刷新
  },
  beforeDestroy() {
    this.stopAutoRefresh();  // 组件销毁前停止定时器
  },
  methods: {
    /** 查询设备数据列表 */
    getList() {
      this.loading = true;
      this.addDateRange(this.queryParams, this.dateRange);
      listDeviceData(this.queryParams).then(response => {
        this.deviceDataList = response.rows || response.data || response;
        this.total = response.total || this.deviceDataList.length;
        this.loading = false;
      }).catch(error => {
        console.error('获取设备数据失败:', error);
        this.$modal.msgError('获取设备数据失败');
        this.loading = false;
      });
    },
    /** 刷新特定传感器数据 */
    refreshSensorData(sensorId) {
      if (sensorId) {
        getDeviceDataBySensorId(sensorId, this.queryParams.pageSize).then(response => {
          // 更新对应传感器的数据
          this.$modal.msgSuccess(`传感器 ${sensorId} 数据已刷新`);
        });
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('emqx/deviceDetails/export', {
        ...this.queryParams
      }, `设备数据_${new Date().getTime()}.xlsx`);
    },
    /** 刷新按钮操作 */
    handleRefresh() {
      this.getList();
      this.$modal.msgSuccess("刷新成功");
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备数据";
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
    sensorId: null,
    appId: null,
    nodeId: null,
    nodeName: null,
    manufacturerId: null,
    model: null,
    longitude: null,
    latitude: null,
    fullName: null,
    proviceCode: null,
    cityCode: null,
    regionCode: null,
    connectStatus: 1,  // 默认为已连接
    status: 1,           // 默认为启用
    description: null,
    remark: null
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addDeviceDetails(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.currentDevice = { ...row };
      this.viewOpen = true;
      this.loadSensorData(row.sensorId);
    },
    
    /** 加载传感器数据 */
    loadSensorData(sensorId) {
      if (!sensorId) {
        this.$modal.msgWarning('传感器ID不能为空');
        return;
      }
      
      this.sensorDataLoading = true;
      getDeviceDataBySensorId(sensorId, 20).then(response => {
        this.sensorDataList = response.data || response || [];
        console.log('传感器数据:', this.sensorDataList);
      }).catch(error => {
        console.error('获取传感器数据失败:', error);
        this.$modal.msgError('获取温湿度数据失败');
        this.sensorDataList = [];
      }).finally(() => {
        this.sensorDataLoading = false;
      });
    },
    
    /** 刷新传感器数据 */
    refreshSensorData() {
      if (this.currentDevice && this.currentDevice.sensorId) {
        this.loadSensorData(this.currentDevice.sensorId);
      }
    },
    
    /** 温度颜色判断 */
    getTemperatureColor(temperature) {
      if (temperature < 10) return '#409EFF'; // 蓝色
      if (temperature < 25) return '#67C23A'; // 绿色
      if (temperature < 35) return '#E6A23C'; // 橙色
      return '#F56C6C'; // 红色
    },
    
    /** 湿度颜色判断 */
    getHumidityColor(humidity) {
      if (humidity < 30) return '#F56C6C'; // 红色
      if (humidity < 60) return '#67C23A'; // 绿色
      if (humidity < 80) return '#E6A23C'; // 橙色
      return '#409EFF'; // 蓝色
    },
    
    /** 开始自动刷新 */
    startAutoRefresh() {
      if (this.autoRefreshEnabled) {
        this.refreshTimer = setInterval(() => {
          this.getList();
          // 如果设备详情对话框打开，也刷新传感器数据
          if (this.viewOpen && this.currentDevice) {
            this.loadSensorData(this.currentDevice.sensorId);
          }
        }, this.refreshInterval);
      }
    },
  
    /** 停止自动刷新 */
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },
    
    /** 切换自动刷新状态 */
    toggleAutoRefresh() {
      this.autoRefreshEnabled = !this.autoRefreshEnabled;
      if (this.autoRefreshEnabled) {
        this.startAutoRefresh();
        this.$message.success('自动刷新已开启');
      } else {
        this.stopAutoRefresh();
        this.$message.info('自动刷新已关闭');
      }
    },
  }
}
</script>

<style scoped>
.info-item {
  margin-bottom: 10px;
}

.info-label {
  font-weight: bold;
  color: #606266;
  margin-right: 8px;
}

.info-value {
  color: #303133;
}

.box-card {
  border-radius: 8px;
}

.el-statistic {
  text-align: center;
}
</style>